{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Matplotlib: lotka volterra tutorial\n",
    "\n",
    "1.  1.  page was renamed from LoktaVolterraTutorial\n",
    "\n",
    "This example describes how to integrate ODEs with the scipy.integrate\n",
    "module, and how to use the matplotlib module to plot trajectories,\n",
    "direction fields and other information.\n",
    "\n",
    "You can get the source code for this tutorial here:\n",
    "[tutorial_lokta-voltera_v4.py](files/attachments/LoktaVolterraTutorial/tutorial_lokta-voltera_v4.py).\n",
    "\n",
    "Presentation of the Lotka-Volterra Model\n",
    "----------------------------------------\n",
    "\n",
    "We will have a look at the Lotka-Volterra model, also known as the\n",
    "predator-prey equations, which is a pair of first order, non-linear,\n",
    "differential equations frequently used to describe the dynamics of\n",
    "biological systems in which two species interact, one a predator and the\n",
    "other its prey. The model was proposed independently by Alfred J. Lotka\n",
    "in 1925 and Vito Volterra in 1926, and can be described by"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "du/dt =  a*u -   b*u*v  \n",
    "dv/dt = -c*v + d*b*u*v"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "with the following notations:\n",
    "\n",
    "*  u: number of preys (for example, rabbits)\n",
    "\n",
    "*  v: number of predators (for example, foxes)  \n",
    "  \n",
    "* a, b, c, d are constant parameters defining the behavior of the population:    \n",
    "\n",
    "  + a is the natural growing rate of rabbits, when there's no fox\n",
    "\n",
    "  + b is the natural dying rate of rabbits, due to predation\n",
    "\n",
    "  + c is the natural dying rate of fox, when there's no rabbit\n",
    "\n",
    "  + d is the factor describing how many caught rabbits let create a new fox"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use X=[u, v] to describe the state of both populations.\n",
    "\n",
    "Definition of the equations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "from numpy import *\n",
    "import pylab as p\n",
    "# Definition of parameters\n",
    "a = 1.\n",
    "b = 0.1\n",
    "c = 1.5\n",
    "d = 0.75\n",
    "def dX_dt(X, t=0):\n",
    "    \"\"\" Return the growth rate of fox and rabbit populations. \"\"\"\n",
    "    return array([ a*X[0] -   b*X[0]*X[1] ,\n",
    "                  -c*X[1] + d*b*X[0]*X[1] ])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Population equilibrium\n",
    "\n",
    "Before using !SciPy to integrate this system, we will have a closer look\n",
    "at position equilibrium. Equilibrium occurs when the growth rate is\n",
    "equal to 0. This gives two fixed points:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "X_f0 = array([     0. ,  0.])\n",
    "X_f1 = array([ c/(d*b), a/b])\n",
    "all(dX_dt(X_f0) == zeros(2) ) and all(dX_dt(X_f1) == zeros(2)) # => True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stability of the fixed points\n",
    "\n",
    "Near these two points, the system can be linearized: dX\\_dt = A\\_f\\*X\n",
    "where A is the Jacobian matrix evaluated at the corresponding point. We\n",
    "have to define the Jacobian matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "def d2X_dt2(X, t=0):\n",
    "    \"\"\" Return the Jacobian matrix evaluated in X. \"\"\"\n",
    "    return array([[a -b*X[1],   -b*X[0]     ],\n",
    "                  [b*d*X[1] ,   -c +b*d*X[0]] ])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So near X\\_f0, which represents the extinction of both species, we have:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#! python\n",
    "A_f0 = d2X_dt2(X_f0)                    # >>> array([[ 1. , -0. ],\n",
    "                                        #            [ 0. , -1.5]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Near X\\_f0, the number of rabbits increase and the population of foxes\n",
    "decrease. The origin is therefore a [saddle\n",
    "point](http://en.wikipedia.org/wiki/Saddle_point).\n",
    "\n",
    "Near X\\_f1, we have:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "A_f1 = d2X_dt2(X_f1)                    # >>> array([[ 0.  , -2.  ],\n",
    "                                        #            [ 0.75,  0.  ]])\n",
    "# whose eigenvalues are +/- sqrt(c*a).j:\n",
    "lambda1, lambda2 = linalg.eigvals(A_f1) # >>> (1.22474j, -1.22474j)\n",
    "# They are imaginary numbers. The fox and rabbit populations are periodic as follows from further\n",
    "# analysis. Their period is given by:\n",
    "T_f1 = 2*pi/abs(lambda1)                # >>> 5.130199"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Integrating the ODE using scipy.integrate\n",
    "-----------------------------------------\n",
    "\n",
    "Now we will use the scipy.integrate module to integrate the ODEs. This\n",
    "module offers a method named odeint, which is very easy to use to\n",
    "integrate ODEs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "from scipy import integrate\n",
    "t = linspace(0, 15,  1000)              # time\n",
    "X0 = array([10, 5])                     # initials conditions: 10 rabbits and 5 foxes\n",
    "X, infodict = integrate.odeint(dX_dt, X0, t, full_output=True)\n",
    "infodict['message']                     # >>> 'Integration successful.'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\\`infodict\\` is optional, and you can omit the \\`full\\_output\\` argument\n",
    "if you don't want it. Type \"info(odeint)\" if you want more information\n",
    "about odeint inputs and outputs.\n",
    "\n",
    "We can now use Matplotlib to plot the evolution of both populations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "rabbits, foxes = X.T\n",
    "f1 = p.figure()\n",
    "p.plot(t, rabbits, 'r-', label='Rabbits')\n",
    "p.plot(t, foxes  , 'b-', label='Foxes')\n",
    "p.grid()\n",
    "p.legend(loc='best')\n",
    "p.xlabel('time')\n",
    "p.ylabel('population')\n",
    "p.title('Evolution of fox and rabbit populations')\n",
    "f1.savefig('rabbits_and_foxes_1.png')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](files/attachments/LoktaVolterraTutorial/rabbits_and_foxes_1v2.png)\n",
    "\n",
    "The populations are indeed periodic, and their period is close to the\n",
    "value T\\_f1 that we computed.\n",
    "\n",
    "Plotting direction fields and trajectories in the phase plane\n",
    "-------------------------------------------------------------\n",
    "\n",
    "We will plot some trajectories in a phase plane for different starting\n",
    "points between X\\_f0 and X\\_f1.\n",
    "\n",
    "We will use Matplotlib's colormap to define colors for the trajectories.\n",
    "These colormaps are very useful to make nice plots. Have a look at\n",
    "[ShowColormaps](http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps)\n",
    "if you want more information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "values  = linspace(0.3, 0.9, 5)                          # position of X0 between X_f0 and X_f1\n",
    "vcolors = p.cm.autumn_r(linspace(0.3, 1., len(values)))  # colors for each trajectory\n",
    "\n",
    "f2 = p.figure()\n",
    "\n",
    "#-------------------------------------------------------\n",
    "# plot trajectories\n",
    "for v, col in zip(values, vcolors): \n",
    "    X0 = v * X_f1                               # starting point\n",
    "    X = integrate.odeint( dX_dt, X0, t)         # we don't need infodict here\n",
    "    p.plot( X[:,0], X[:,1], lw=3.5*v, color=col, label='X0=(%.f, %.f)' % ( X0[0], X0[1]) )\n",
    "\n",
    "#-------------------------------------------------------\n",
    "# define a grid and compute direction at each point\n",
    "ymax = p.ylim(ymin=0)[1]                        # get axis limits\n",
    "xmax = p.xlim(xmin=0)[1] \n",
    "nb_points   = 20                      \n",
    "\n",
    "x = linspace(0, xmax, nb_points)\n",
    "y = linspace(0, ymax, nb_points)\n",
    "\n",
    "X1 , Y1  = meshgrid(x, y)                       # create a grid\n",
    "DX1, DY1 = dX_dt([X1, Y1])                      # compute growth rate on the gridt\n",
    "M = (hypot(DX1, DY1))                           # Norm of the growth rate \n",
    "M[ M == 0] = 1.                                 # Avoid zero division errors \n",
    "DX1 /= M                                        # Normalize each arrows\n",
    "DY1 /= M                                  \n",
    "\n",
    "#-------------------------------------------------------\n",
    "# Drow direction fields, using matplotlib 's quiver function\n",
    "# I choose to plot normalized arrows and to use colors to give information on\n",
    "# the growth speed\n",
    "p.title('Trajectories and direction fields')\n",
    "Q = p.quiver(X1, Y1, DX1, DY1, M, pivot='mid', cmap=p.cm.jet)\n",
    "p.xlabel('Number of rabbits')\n",
    "p.ylabel('Number of foxes')\n",
    "p.legend()\n",
    "p.grid()\n",
    "p.xlim(0, xmax)\n",
    "p.ylim(0, ymax)\n",
    "f2.savefig('rabbits_and_foxes_2.png')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](files/attachments/LoktaVolterraTutorial/rabbits_and_foxes_2v3.png)\n",
    "\n",
    "This graph shows us that changing either the fox or the rabbit\n",
    "population can have an unintuitive effect. If, in order to decrease the\n",
    "number of rabbits, we introduce foxes, this can lead to an increase of\n",
    "rabbits in the long run, depending on the time of intervention.\n",
    "\n",
    "Plotting contours\n",
    "-----------------\n",
    "\n",
    "We can verify that the function IF defined below remains constant along\n",
    "a trajectory:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "def IF(X):\n",
    "    u, v = X\n",
    "    return u**(c/a) * v * exp( -(b/a)*(d*u+v) )\n",
    "# We will verify that IF remains constant for different trajectories\n",
    "for v in values:\n",
    "    X0 = v * X_f1                               # starting point\n",
    "    X = integrate.odeint( dX_dt, X0, t)\n",
    "    I = IF(X.T)                                 # compute IF along the trajectory\n",
    "    I_mean = I.mean()\n",
    "    delta = 100 * (I.max()-I.min())/I_mean\n",
    "    print 'X0=(%2.f,%2.f) => I ~ %.1f |delta = %.3G %%' % (X0[0], X0[1], I_mean, delta)\n",
    "# >>> X0=( 6, 3) => I ~ 20.8 |delta = 6.19E-05 %\n",
    "#     X0=( 9, 4) => I ~ 39.4 |delta = 2.67E-05 %\n",
    "#     X0=(12, 6) => I ~ 55.7 |delta = 1.82E-05 %\n",
    "#     X0=(15, 8) => I ~ 66.8 |delta = 1.12E-05 %\n",
    "#     X0=(18, 9) => I ~ 72.4 |delta = 4.68E-06 %"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plotting iso-contours of IF can be a good representation of\n",
    "trajectories, without having to integrate the ODE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#!python\n",
    "#-------------------------------------------------------\n",
    "# plot iso contours\n",
    "nb_points = 80                              # grid size\n",
    "x = linspace(0, xmax, nb_points)\n",
    "y = linspace(0, ymax, nb_points)\n",
    "X2 , Y2  = meshgrid(x, y)                   # create the grid\n",
    "Z2 = IF([X2, Y2])                           # compute IF on each point\n",
    "f3 = p.figure()\n",
    "CS = p.contourf(X2, Y2, Z2, cmap=p.cm.Purples_r, alpha=0.5)\n",
    "CS2 = p.contour(X2, Y2, Z2, colors='black', linewidths=2. )\n",
    "p.clabel(CS2, inline=1, fontsize=16, fmt='%.f')\n",
    "p.grid()\n",
    "p.xlabel('Number of rabbits')\n",
    "p.ylabel('Number of foxes')\n",
    "p.ylim(1, ymax)\n",
    "p.xlim(1, xmax)\n",
    "p.title('IF contours')\n",
    "f3.savefig('rabbits_and_foxes_3.png')\n",
    "p.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](files/attachments/LoktaVolterraTutorial/rabbits_and_foxes_3v2.png)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
